﻿using Max.PH6_2006A.LowCode.Domain;
using Max.PH6_2006A.LowCode.IService;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using NPOI.SS.UserModel;

namespace Max.PH6_2006A.LowCode.API.Controllers
{
    /// <summary>
    /// 员工控制器
    /// </summary>
    [Route("hr/employee")]
    [ApiController]
    public class EmployeeController : BaseCRUDController<Employee, Employee, Employee> //ControllerBase
    {
        Microsoft.AspNetCore.Hosting.IWebHostEnvironment _host;
        IEmployeeService _employeeService;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="host"></param>
        /// <param name="employeeService"></param>
        public EmployeeController(Microsoft.AspNetCore.Hosting.IWebHostEnvironment host, IEmployeeService employeeService):base(employeeService)
        {
            _host = host;
            _employeeService = employeeService;
        }

        ///// <summary>
        ///// 员工列表信息
        ///// </summary>
        ///// <param name="employeeNo"></param>
        ///// <param name="pageIndex"></param>
        ///// <param name="pageSize"></param>
        ///// <returns></returns>
        //[HttpGet("query")]
        //public async Task<IActionResult> QueryAsync(string? employeeNo, int pageIndex = 1, int pageSize = 20)
        //{
        //    //问:
        //    //dapper中，如何实现模糊查询（根据员工工号模糊查询）

        //    DTO.ApiResultReturnDto dto = new DTO.ApiResultReturnDto();
        //    var result = await _employeeService.QueryAsync(pageIndex, pageSize, "select * from Employee");
        //    dto.Data = new { items = result.Item1, total = result.Item2 };
        //    return Ok(dto);
        //}

        /// <summary>
        /// 导入员工信息
        /// </summary>
        /// <param name="isCreateUser">是否生成系统账号</param>
        /// <returns></returns>
        [HttpPost("import")]
        public async Task<IActionResult> ImportAsync(bool isCreateUser = true)
        {
            DTO.ApiResultReturnDto dto = new();

            var file = Request.Form.Files;
            if (file == null || file.Count <= 0) {
                dto.Code = DTO.ApiResultReturnCode.Failed;
                dto.Message = "未选择文件!";
                return BadRequest(dto);
            }
            var result = await _employeeService.ImportAsync(file, isCreateUser);
           
            //上传成功
            if(result.Item1)
                dto.Data = result.Item2;
            else
            {
                //上传失败
                dto.Code = DTO.ApiResultReturnCode.Failed;
                dto.Message = result.Item2;
            }
            return Ok(result);
        }

        /// <summary>
        /// 导出所有数据
        /// </summary>
        /// <returns></returns>
        [HttpGet("export")]
        public async Task<IActionResult> ExportAsync()
        {
            //1、从数据库读取数据
            var list = await _employeeService.QueryAsync("select * from employee");

            string filePath = "";

            #region //2、将数据写入到Excel

            var wwwroot = _host.WebRootPath;
            var fileName = "员工信息.xlsx";
            filePath = Path.Combine(wwwroot, fileName);

            //var stream = System.IO.File.Create(filePath);
            //IWorkbook book = WorkbookFactory.Create();

            NPOI.XSSF.UserModel.XSSFWorkbook book = new NPOI.XSSF.UserModel.XSSFWorkbook();

            //默认只创建一个sheet
            var sheet = book.CreateSheet();

            //excel是表格：分表头和数据行,表头默认是第一行
            //表头行
            var headerRow = sheet.CreateRow(0);
            headerRow.CreateCell(0).SetCellValue("姓名1");
            headerRow.CreateCell(1).SetCellValue("姓名2");
            headerRow.CreateCell(2).SetCellValue("姓名3");
            headerRow.CreateCell(3).SetCellValue("姓名4");

            //数据行(第二行开始。有多少数据就有多少行)
            var data = list.ToList();
            for (int i = 0; i < data.Count; i++)
            {
                var dataRow =  sheet.CreateRow(i+1);
                dataRow.CreateCell(0).SetCellValue(data[i].Name);
                dataRow.CreateCell(1).SetCellValue(data[i].EmployeeNo);
                dataRow.CreateCell(2).SetCellValue(Convert.ToString( data[i].CreatedTime));
                dataRow.CreateCell(3).SetCellValue(Convert.ToString(data[i].Id));
            }

            using (var f = System.IO.File.OpenWrite(filePath))
            {
                book.Write(f);
            }

            #endregion

            //3、下载这个excel
            var bytes = System.IO.File.ReadAllBytes(filePath);
            return File(bytes, "application/octet-stream", $"{System.DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx");
        }

        /// <summary>
        /// 下载导入的文件模板
        /// </summary>
        /// <returns></returns>
        [HttpGet("download")]
        public async Task<IActionResult> DownloadTemplateAsync()
        {
            DTO.ApiResultReturnDto dto = new();
            var wwwroot = _host.WebRootPath;
            string fileName = "employee(template).xlsx";
            string filePath = Path.Combine(wwwroot,fileName);

            if(!System.IO.File.Exists(filePath))
            {
                dto.Code = DTO.ApiResultReturnCode.Failed;
                dto.Message = "模板文件不存在，请联系管理员";
                return BadRequest(dto);
            }

            var ms = await System.IO.File.ReadAllBytesAsync(filePath);
            return File(ms, "application/octet-stream", $"{System.DateTime.Now.ToString("yyyyMMdd")}.xlsx");
        }
    }
}
